package org.example.system.interceptor;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.JwtUtil;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 在访问接口之前拦截，判断用户的令牌（token）是否合法
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        log.info("--------------JwtInterceptor | preHandle | token：{}",token);
        if (null != token && token.startsWith("Bearer")){//如果token存在且以Bearer开头
            //处理token
            token = token.replace("Bearer","").trim();
            try{
                String payload = JwtUtil.get(token);//如果token不合法，这行代码会报错
                log.info("--------------JwtInterceptor | preHandle | payload：{}",payload);
                String key = "LOGIN_USER_TOKEN:" + payload;
                String existToken = (String)redisTemplate.opsForValue().get(key);
                //如果客户端传过来的token和redis的token一样，用户现在是真正的登录状态，延长登录状态
                if (null != existToken && existToken.equals(token)){
                    redisTemplate.expire(key,30, TimeUnit.MINUTES);
                    return true;
                }
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
        //代码走到了这里，token一定是不合法的
        String result = JSON.toJSONString(R.fail(401,"登录状态失败，请重新登录"));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(result);
        response.getWriter().flush();
        return true;
    }
}
